//处理指令成ASCII码，然后再转化二进制
export const dataTransforma = (data: string, direct: any) => {
  const buffer = new ArrayBuffer(data.length)
  const dataView = new DataView(buffer)
  for (let i = 0; i < data.length; i++) {
    dataView.setUint8(i, data.charCodeAt(i))
  }
  direct = buffer
  //console.log(direct.value)
}

//调用特征值发送指令  走写入通道
export const BleWrite = (
    deviceId: string,
    serviceId: string,
    characteristicId: string,
    buffer: ArrayBuffer,
  ) => {
    console.log(buffer)
    const res = uni.writeBLECharacteristicValue({
      deviceId,
      serviceId,
      characteristicId,
      value: buffer, // 这里的value是ArrayBuffer类型
      writeType: 'write',
      success(res) {
        console.log('指令发送成功', res)
      },
      fail(err) {
        console.log('指令发送失败', err)
        uni.showToast({
          title: '蓝牙指令发送失败',
          icon: 'none',
        })
      },
    })
  }

  export const notifyBLECharacteristicValueChange = (
    deviceId: string,
    serviceId: string,
    characteristicId: string,
  ) => {
    uni.notifyBLECharacteristicValueChange({
      deviceId,
      serviceId,
      characteristicId,
      state: true,
      success: (res) => {
        console.log(res)
        //监听设备发送数据
        uni.onBLECharacteristicValueChange((res) => {
          console.log(res.value)
          formatConversion(new Uint8Array(res.value))
        })
      },
      fail: (err) => {
        console.log(err)
      },
    })
  }